package com.cbtx.utils

import android.content.Context
import com.google.gson.Gson
import org.json.JSONException
import org.json.JSONObject
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.util.*

/**
 * author : joker.peng
 * e-mail : joker@fiture.com
 * date   : 2021/7/7 12:11 AM
 * desc   :
 */
object GsonUtil {

    var gson: Gson? = null

    /**
     * json解析
     *
     * @param json 字符串格式的json
     * @param clz  对象名
     * @return
     */
    fun <T> jsonToBean(json: String?, clz: Class<T>?): T {
        val mGson = Gson()
        return mGson.fromJson(json, clz)
    }

    /**
     * json解析
     *
     * @param obj  对象名
     * @return
     */
    fun <T> beanToJson(obj: T): String? {
        val mGson = Gson()
        return mGson.toJson(obj)
    }

    /**
     * 将map数据解析出来，并拼接成json字符串
     *
     * @param map
     * @return
     */
    @Throws(Exception::class)
    fun setJosn(map: Map<*, *>): String {
        var temp = StringBuffer()
        if (!map.isEmpty()) {
            temp.append("{")
            // 遍历map
            val set: Set<*> = map.entries
            val i = set.iterator()
            while (i.hasNext()) {
                val entry = i.next() as Map.Entry<*, *>
                val key = entry.key as String
                val value = entry.value!!
                temp.append("\"$key\":")
                if (value is Map<*, *>) {
                    temp.append(setJosn(value as Map<String?, Any?>) + ",")
                } else if (value is List<*>) {
                    temp.append(
                        setList(value as List<Map<String?, Any?>>)
                                + ","
                    )
                } else {
                    temp.append("\"$value\",")
                }
            }
            if (temp.length > 1) {
                temp = StringBuffer(temp.substring(0, temp.length - 1))
            }
            temp.append("}")
        }
        return temp.toString()
    }

    /**
     * 将单个list转成json字符串
     *
     * @param list
     * @return
     * @throws Exception
     */
    @Throws(Exception::class)
    fun setList(list: List<Map<String?, Any?>>): String {
        var jsonL = ""
        var temp = StringBuffer()
        temp.append("[")
        for (i in list.indices) {
            val m = list[i]
            if (i == list.size - 1) {
                temp.append(setJosn(m))
            } else {
                temp.append(setJosn(m) + ",")
            }
        }
        if (temp.length > 1) {
            temp = StringBuffer(temp.substring(0, temp.length))
        }
        temp.append("]")
        jsonL = temp.toString()
        return jsonL
    }

    /**
     * 将json格式的字符串解析成Map对象  *
     */
    fun toHashMap(`object`: String?): HashMap<String, Any>? {
        val data = HashMap<String, Any>()
        // 将json字符串转换成jsonObject
        val jsonObject: JSONObject
        try {
            jsonObject = JSONObject(`object`)
            val it: Iterator<*> = jsonObject.keys()
            // 遍历jsonObject数据，添加到Map对象
            while (it.hasNext()) {
                val key = it.next().toString()
                val value = jsonObject[key]
                data[key] = value
            }
            return data
        } catch (e: JSONException) {
            // TODO Auto-generated catch block
            e.printStackTrace()
        }
        return null
    }

    fun getInstance(): Gson? {
        if (gson == null) {
            synchronized(Gson::class.java) {
                if (gson == null) {
                    gson = Gson()
                }
            }
        }
        return gson
    }


    /**
     * 读取json
     *
     * @param context
     * @param fileName
     * @return
     */
    fun getJson(context: Context, fileName: String?): String? {
        val stringBuilder = StringBuilder()
        try {
            val assetManager = context.assets
            val bf = BufferedReader(
                InputStreamReader(
                    assetManager.open(fileName!!)
                )
            )
            var line: String?
            while (bf.readLine().also { line = it } != null) {
                stringBuilder.append(line)
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return stringBuilder.toString()
    }
}